package com.jsea.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsea.common.FileInfoPO;
import com.jsea.common.dto.ResultDTO;
import com.jsea.service.IFileService;

@RestController
@RequestMapping("file/{fileType}")
public class FileServerAPI {
	
	@Resource
	IFileService fileService;
	
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public void upload(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileType,
			String limitSuffix, String limitSize) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		ResultDTO result = null;
		ObjectMapper mapper = new ObjectMapper();
		if (!ServletFileUpload.isMultipartContent(request)) {
			result = new ResultDTO("上传文件格式不正确！", null);
			out.print(mapper.writeValueAsString(result));
			out.close();
			return;
		}

		String userID = "0000";
		try {

			Map<String, String> limitSuffixMap = new HashMap<String, String>();
			// 如果有尾缀限制
			if (limitSuffix != null && !limitSuffix.trim().equals("")) {
				String[] limitSuffixList = limitSuffix.split(",");
				for (int i = 0; i < limitSuffixList.length; i++) {
					limitSuffixMap.put(limitSuffixList[i].toLowerCase(), "");
				}
			}

			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> fileList = multipartRequest.getFiles("files[]");
			if (fileList == null || fileList.size() == 0) {
				throw new Exception("系统没有检测到上传的文件");
			}

			MultipartFile file = fileList.get(0);

			if (file.isEmpty()) {
				throw new Exception("系统没有检测到上传的文件");
			}
			// 如果有大小限制,单位M
			if (limitSize != null && !limitSize.trim().equals("")) {
				// 取得文件尾缀
				if (Integer.parseInt(limitSize) * 1024 * 1024 < Integer.valueOf(String.valueOf(file.getSize()))) {
					throw new Exception("上传的单个文件大小不能超过" + limitSize + "M");
				}
			}
			String fileName = file.getOriginalFilename();
			if (fileName.indexOf("\\") != -1) {
				fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
			}

			if (fileName.indexOf("'") != -1) {
				throw new Exception("上传的文件名称中不能包含单引号");
			}
			// 如果有尾缀限制
			if (limitSuffix != null && !limitSuffix.trim().equals("")) {
				// 取得文件尾缀
				int lastPointIndex = fileName.lastIndexOf(".");
				if (lastPointIndex == -1) {
					throw new Exception("上传的文件必须为" + limitSuffix + "格式的文件。");
				}
				String fileSuffix = fileName.substring(lastPointIndex + 1);
				if (!limitSuffixMap.containsKey(fileSuffix.toLowerCase())) {
					throw new Exception("上传的文件必须为" + limitSuffix + "格式的文件。");
				}
			}

			result = new ResultDTO(fileService.upload(file, userID));

			out.print(mapper.writeValueAsString(result));
		} catch (Exception e) {
			e.printStackTrace();
			result = new ResultDTO(e.getMessage(), null);
			out.print(mapper.writeValueAsString(result));
		} finally {
			out.flush();
			out.close();
		}
	}
	
	@RequestMapping(value = "/download/{fileID}", method = RequestMethod.GET)
	public void download(HttpServletResponse response, @PathVariable String fileID) throws IOException {
		FileInfoPO fileInfo = fileService.download(fileID);
		if (fileInfo == null) {
			return;
		}
		response.reset();
		
		ServletOutputStream out = response.getOutputStream();
		File file = new File(fileInfo.getFilePath());
		if (null == file || !file.exists()) {
			return;
		}
		
		String fileName = new String(fileInfo.getFileName().getBytes("GBK"), "ISO-8859-1");
		response.setContentType("application/force-download");
		response.setHeader("Content-Disposition", "attachment; fileName=" + fileName);
		response.addHeader("Content-Length", "" + fileInfo.getFileSize());
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Expires", "0");

		InputStream fileStream = new FileInputStream(file);
		byte[] buff = new byte[1024];
		int len = -1;
		while ((len = fileStream.read(buff)) != -1) {
			out.write(buff, 0, len);
		}
		out.flush();
		out.close();
		fileStream.close();
	}
}
